const path = require('path')
const Koa = require('koa')
const JWT = require('koa-jwt')
const helmet = require('koa-helmet')
const statics = require('koa-static')
const koaBody = require('koa-body')
const cors = require('@koa/cors')
const compose = require('koa-compose')
const router = require('./routes/routes')
const compress = require('koa-compress')
const { JWT_SECRET } = require('./config')
const errorHandle = require('./common/errorHandle')
const app = new Koa()
const isProdMode = process.env.NODE_ENV === 'production'
const port = isProdMode ? 11010 : 3000
if (isProdMode) {
  app.use(compress())
}

// 定义公共路径，不需要jwt鉴权
const jwt = JWT({ secret: JWT_SECRET }).unless({ path: [/^\/public/, /\/login/] })
console.log(__dirname)
console.log(path.join(__dirname, '../public'))
const middleware = compose([
  koaBody(),
  statics(path.join(__dirname, '../public')),
  cors(),
  helmet(),
  errorHandle,
  jwt
])
app.use(middleware)
app.use(router())
app.listen(port, () => {
  console.log(`The server is running at:${port}`)
})
